import torch
from torch.nn import L1Loss, MSELoss, CrossEntropyLoss

inputs = torch.tensor([1, 2, 3], dtype=torch.float32)
targets = torch.tensor([1, 2, 5], dtype=torch.float32)

# 不需要reshape()也可以
inputs = torch.reshape(inputs, (1, 1, 1, 3))
targets = torch.reshape(targets, (1, 1, 1, 3))

l1loss = L1Loss(reduction='mean')
output = l1loss(inputs, targets)

mseloss = MSELoss()
mse_output = mseloss(inputs, targets)

print(output)
print(mse_output)

x = torch.tensor([0.1, 0.2, 0.3])
x = x.reshape((1, -1))
y = torch.tensor([1])

# -0.2 + log(exp(0.1) + exp(0.2) + exp(0.3))
cel = CrossEntropyLoss()
z = cel(x, y)
print(z)

from torchvision import transforms
from torchvision.datasets import CIFAR10
from torch.nn import Linear, Module, Flatten, MaxPool2d, Conv2d, Sequential
import torch

dataset = CIFAR10(root="./dataset", train=False, transform=transforms.ToTensor())
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True)

class MyCifarModel(Module):
    def __init__(self):
        super(MyCifarModel, self).__init__()
        self.model1 = Sequential(
            Conv2d(3, 32, 3, padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self, x):
        return self.model1(x)

my_model = MyCifarModel()
cel = CrossEntropyLoss()

for data in dataloader:
    imgs, labels = data
    outputs = my_model(imgs)
    loss = cel(outputs, labels)
    # 使用损失函数进行反向传播
    loss.backward()
    print(loss)
